package Demo09;

import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);
        System.out.println("程序开始执行");
    }
}

class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable runnable;
    private long curTime;

    MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        curTime = System.currentTimeMillis() + delay;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getCurTime() {
        return curTime;
    }

    @Override
    public int compareTo(MyTimerTask o2) {
        //小根堆, 最小的在前面
        return (int) (this.curTime - o2.curTime);
    }
}

class MyTimer {
    //使用优先级队列, 优先处理时间最小的任务
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            queue.offer(new MyTimerTask(runnable, delay));
            locker.notify();
        }
    }

    MyTimer() {
        Thread t = new Thread(() -> {
            //反复检查是否到达事件
            while (true) {
                //检查队列是否非空
                //wait尽量搭配while使用, 每次唤醒都要再次检查是否条件满足
                synchronized (locker) {
                    while (queue.isEmpty()) {
                        //队列为空, 等待队列有元素进入
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //当前时间
                    long curTime =  System.currentTimeMillis();
                    MyTimerTask task = queue.peek();
                    if (task.getCurTime() > curTime) {
                        //时间还没到, 就进行等待, 不然也是忙等, 一直在不停的判断
                        //这里不能使用sleep, 因为使用sleep后, 当出现一个比时间最小任务时间更小的时候
                        //因为此时处于沉睡状态, 所以不能被加入到队列也不能被执行
                        try {
                            locker.wait(task.getCurTime() - curTime);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        //时间到了
                        task.getRunnable().run();
                        queue.poll();
                    }
                }
            }
        });
        t.start();
    }
}